<template>
  <div class="page-container">
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <h3>自定义节点类型管理</h3>
          <el-button type="primary" @click="createNewNodeType">
            <el-icon><el-icon-plus /></el-icon> 创建新节点类型
          </el-button>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="customNodeTypes"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="ID" width="180" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column label="使用此节点的事件" width="300">
          <template #default="{ row }">
            <div v-if="loadingUsage[row.id]" class="usage-loading">
              <el-skeleton :rows="1" animated />
            </div>
            <div v-else-if="nodeTypeUsage[row.id]" class="event-usage-list">
              <div v-if="nodeTypeUsage[row.id].length === 0" class="no-usage">
                暂无事件使用此节点类型
              </div>
              <template v-else>
                <div class="event-tag-list">
                  <router-link 
                    v-for="(event, index) in nodeTypeUsage[row.id].slice(0, 10)"
                    :key="event.id"
                    :to="`/events/${event.id}`"
                    class="event-link"
                  >
                    <el-tag size="small" class="event-tag">{{ event.name }}</el-tag>
                  </router-link>
                  <el-button 
                    v-if="nodeTypeUsage[row.id].length > 10" 
                    type="primary" 
                    size="small" 
                    text 
                    @click="showAllUsageEvents(row.id)"
                  >
                    更多 ({{ nodeTypeUsage[row.id].length - 10 }}+)
                  </el-button>
                </div>
              </template>
            </div>
            <el-button v-else type="primary" size="small" text @click="loadNodeTypeUsage(row.id)">
              查看引用
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="当前版本" width="120">
          <template #default="{ row }">
            <template v-if="row.currentVersion">
              <el-tag type="success">v{{ row.currentVersion }}</el-tag>
              <el-tooltip content="已发布，可直接在事件中使用" placement="top">
                <el-icon class="version-icon"><el-icon-check /></el-icon>
              </el-tooltip>
            </template>
            <el-tag v-else type="info">未发布</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.published ? 'success' : 'info'">
              {{ row.published ? '已发布' : '未发布' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="viewNodeType(row)">
              详情
            </el-button>
            <el-button size="small" type="success" @click="viewVersions(row)">
              版本管理
            </el-button>
            <el-button size="small" type="danger" @click="confirmDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="customNodeTypes.length === 0 && !loading" class="empty-data">
        <el-empty description="暂无自定义节点类型">
          <el-button type="primary" @click="createNewNodeType">
            创建新节点类型
          </el-button>
        </el-empty>
      </div>
    </el-card>
    
    <!-- 创建/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑节点类型' : '创建节点类型'"
      width="500px"
    >
      <el-form :model="form" label-width="100px" ref="formRef" :rules="formRules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="输入节点类型名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            placeholder="输入节点类型描述"
            rows="3"
          />
        </el-form-item>
        <el-form-item label="参数说明" prop="parametersDocs">
          <el-input 
            v-model="form.parametersDocs" 
            type="textarea" 
            placeholder="参数说明，描述此节点类型接收哪些参数"
            rows="3"
          />
        </el-form-item>
        <el-form-item label="返回值说明" prop="returnDocs">
          <el-input 
            v-model="form.returnDocs" 
            type="textarea" 
            placeholder="返回值说明，描述此节点类型返回什么结果"
            rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveNodeType" :loading="submitting">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 所有引用事件对话框 -->
    <el-dialog
      v-model="allUsageDialogVisible"
      title="引用此节点类型的所有事件"
      width="700px"
      append-to-body
    >
      <div v-if="currentNodeTypeUsage">
        <el-table 
          :data="allUsageEvents.events" 
          style="width: 100%" 
          border
          v-loading="loadingAllUsage"
        >
          <el-table-column prop="name" label="事件名称" />
          <el-table-column prop="category" label="分类" />
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <router-link :to="`/events/${row.id}`">
                <el-button type="primary" size="small">查看</el-button>
              </router-link>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="usagePagination.currentPage"
            v-model:page-size="usagePagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="allUsageEvents.total"
            @size-change="handleUsageSizeChange"
            @current-change="handleUsagePageChange"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus as ElIconPlus, Check as ElIconCheck } from '@element-plus/icons-vue'

const store = useStore()
const router = useRouter()

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const isEditing = ref(false)
const formRef = ref(null)

const form = ref({
  name: '',
  description: '',
  parametersDocs: '',
  returnDocs: ''
})

const formRules = {
  name: [{ required: true, message: '请输入节点类型名称', trigger: 'blur' }]
}

const customNodeTypes = computed(() => store.state.customNodeTypes)

// 节点类型使用统计
const loadingUsage = ref({})
const nodeTypeUsage = computed(() => store.state.customNodeTypeUsage)

// 全部引用事件对话框
const allUsageDialogVisible = ref(false)
const currentNodeTypeId = ref(null)
const loadingAllUsage = ref(false)
const usagePagination = ref({
  currentPage: 1,
  pageSize: 10
})

// 当前选中的节点类型使用信息
const currentNodeTypeUsage = computed(() => {
  if (!currentNodeTypeId.value) return null
  return nodeTypeUsage.value[currentNodeTypeId.value]
})

// 所有引用事件（分页）
const allUsageEvents = ref({
  events: [],
  total: 0
})

// 获取自定义节点类型列表
const fetchNodeTypes = async () => {
  loading.value = true
  try {
    await store.dispatch('fetchCustomNodeTypes')
  } catch (error) {
    ElMessage.error('获取自定义节点类型列表失败')
  } finally {
    loading.value = false
  }
}

// 创建新节点类型
const createNewNodeType = () => {
  isEditing.value = false
  form.value = {
    name: '',
    description: '',
    parametersDocs: '',
    returnDocs: ''
  }
  dialogVisible.value = true
}

// 查看节点类型详情
const viewNodeType = (nodeType) => {
  router.push(`/custom-nodes/${nodeType.id}`)
}

// 查看版本管理
const viewVersions = (nodeType) => {
  router.push(`/custom-nodes/${nodeType.id}/versions`)
}

// 确认删除节点类型
const confirmDelete = (nodeType) => {
  ElMessageBox.confirm(
    `确认删除节点类型 "${nodeType.name}"？此操作不可恢复！`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const result = await store.dispatch('deleteCustomNodeType', nodeType.id)
      if (result) {
        ElMessage.success('删除成功')
      } else {
        ElMessage.error('删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 保存节点类型
const saveNodeType = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        if (isEditing.value) {
          await store.dispatch('updateCustomNodeType', {
            id: form.value.id,
            nodeType: form.value
          })
          ElMessage.success('更新成功')
        } else {
          // 新增自定义节点类型
          const result = await store.dispatch('createCustomNodeType', {
            ...form.value,
            createTime: new Date().toLocaleDateString(),
            published: false
          })
          ElMessage.success('创建成功')
          
          // 创建成功后跳转到详情页面
          if (result && result.id) {
            router.push(`/custom-nodes/${result.id}`)
          }
        }
        dialogVisible.value = false
      } catch (error) {
        ElMessage.error(isEditing.value ? '更新失败' : '创建失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 加载节点类型使用情况
const loadNodeTypeUsage = async (nodeTypeId) => {
  if (loadingUsage.value[nodeTypeId]) return
  
  loadingUsage.value[nodeTypeId] = true
  try {
    await store.dispatch('fetchCustomNodeTypeUsage', {
      nodeTypeId,
      page: 1,
      pageSize: 100 // 先获取较多数据，以便显示前10个和总数
    })
  } catch (error) {
    ElMessage.error('获取节点类型使用情况失败')
  } finally {
    loadingUsage.value[nodeTypeId] = false
  }
}

// 显示所有引用事件
const showAllUsageEvents = async (nodeTypeId) => {
  currentNodeTypeId.value = nodeTypeId
  usagePagination.value.currentPage = 1
  allUsageDialogVisible.value = true
  await loadAllUsageEvents()
}

// 加载所有引用事件（分页）
const loadAllUsageEvents = async () => {
  if (!currentNodeTypeId.value) return
  
  loadingAllUsage.value = true
  try {
    const result = await store.dispatch('fetchCustomNodeTypeUsage', {
      nodeTypeId: currentNodeTypeId.value,
      page: usagePagination.value.currentPage,
      pageSize: usagePagination.value.pageSize
    })
    allUsageEvents.value = result
  } catch (error) {
    ElMessage.error('获取节点类型使用情况失败')
  } finally {
    loadingAllUsage.value = false
  }
}

// 处理分页大小变化
const handleUsageSizeChange = (size) => {
  usagePagination.value.pageSize = size
  loadAllUsageEvents()
}

// 处理页码变化
const handleUsagePageChange = (page) => {
  usagePagination.value.currentPage = page
  loadAllUsageEvents()
}

onMounted(() => {
  fetchNodeTypes()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}

.version-icon {
  margin-left: 5px;
  color: #67c23a;
  vertical-align: middle;
}

.event-usage-list {
  display: flex;
  flex-direction: column;
}

.event-tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
}

.event-link {
  text-decoration: none;
}

.event-tag {
  cursor: pointer;
}

.no-usage {
  color: #909399;
  font-size: 13px;
}

.usage-loading {
  padding: 0 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 